import Cookies from "js-cookie";
import { storageSession } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";

export interface DataInfo<T> {
  userPhone: any[];
  userNiChen: string;
  userHeader: string;
  userId: string;
  id: number | string;
  /** token */
  accessToken: string;
  /** `accessToken`的过期时间（时间戳） */
  expires: T;
  /** 用于调用刷新accessToken的接口时所需的token */
  refreshToken: string;
  /** 用户名 */
  userAccount?: string;
  /** 当前登陆用户的角色 */
  roles?: Array<string>;
  isAdmin: boolean;
  loginUrl: string;
  appID: number; //看板的应用ID
  appName: string; //看板对应的APPName
  dvID: number; //看板的ID
  appInfoForm: any;
  companyID: number;
  aiFalg: number;
  comID: string;
}

export const sessionKey = "user-info";
export const TokenKey = "authorized-token";

/** 获取`token` */
export function getToken(): DataInfo<number> {
  // 此处与`TokenKey`相同，此写法解决初始化时`Cookies`中不存在`TokenKey`报错

  return Cookies.get(TokenKey)
    ? JSON.parse(Cookies.get(TokenKey))
    : storageSession().getItem(sessionKey);
}

/**
 * @description 设置`token`以及一些必要信息并采用无感刷新`token`方案
 * 无感刷新：后端返回`accessToken`（访问接口使用的`token`）、`refreshToken`（用于调用刷新`accessToken`的接口时所需的`token`，`refreshToken`的过期时间（比如30天）应大于`accessToken`的过期时间（比如2小时））、`expires`（`accessToken`的过期时间）
 * 将`accessToken`、`expires`这两条信息放在key值为authorized-token的cookie里（过期自动销毁）
 * 将`username`、`roles`、`refreshToken`、`expires`这四条信息放在key值为`user-info`的sessionStorage里（浏览器关闭自动销毁）
 */
export function setToken(data: DataInfo<Date>) {
  let expires = 0;
  const { accessToken, refreshToken } = data;
  expires = new Date(data.expires).getTime(); // 如果后端直接设置时间戳，将此处代码改为expires = data.expires，然后把上面的DataInfo<Date>改成DataInfo<number>即可
  const cookieString = JSON.stringify({ accessToken, expires });

  expires > 0
    ? Cookies.set(TokenKey, cookieString, {
        expires: (expires - Date.now()) / 86400000
      })
    : Cookies.set(TokenKey, cookieString);

  function setSessionKey(
    userAccount: string,
    roles: Array<string>,
    id: any,
    userNiChen: any,
    userPhone: any,
    isAdmin: boolean,
    userHeader: string,
    loginUrl: string,
    companyID: number,
    aiFalg: number,
    comID: string
  ) {
    useUserStoreHook().SET_USERNAME(userAccount);
    useUserStoreHook().SET_COMID(comID);
    useUserStoreHook().SET_COMPANYID(companyID);
    useUserStoreHook().SET_AIFALG(aiFalg);
    useUserStoreHook().SET_ROLES(roles);
    useUserStoreHook().SET_ID(id);
    useUserStoreHook().SET_USERNICHENG(userNiChen);
    useUserStoreHook().SET_ISADMIN(isAdmin);
    useUserStoreHook().SET_USERHEADER(userHeader);
    useUserStoreHook().SET_LOGINURL(loginUrl);
    storageSession().setItem(sessionKey, {
      refreshToken,
      expires,
      userAccount,
      roles,
      id,
      userNiChen,
      userPhone,
      isAdmin,
      userHeader,
      companyID,
      aiFalg,
      comID
    });
  }

  if (data.userAccount && data.roles && data.id) {
    const {
      userAccount,
      roles,
      id,
      userNiChen,
      userPhone,
      isAdmin,
      userHeader,
      loginUrl,
      companyID,
      aiFalg,
      comID
    } = data;
    setSessionKey(
      userAccount,
      roles,
      id,
      userNiChen,
      userPhone,
      isAdmin,
      userHeader,
      loginUrl,
      companyID,
      aiFalg,
      comID
    );
  } else {
    const userAccount =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userAccount ?? "";
    const roles =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.roles ?? [];
    const id = storageSession().getItem<DataInfo<number>>(sessionKey)?.id ?? [];
    const userNiChen =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userNiChen ?? "";
    const userPhone =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userPhone ?? [];
    const isAdmin =
      storageSession().getItem<DataInfo<boolean>>(sessionKey)?.isAdmin ?? false;
    const loginUrl =
      storageSession().getItem<DataInfo<boolean>>(sessionKey)?.loginUrl ?? "";
    const userHeader =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userHeader ?? "";
    const companyID =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.companyID ?? 0;
    const aiFalg =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.aiFalg ?? 0;
    const comID =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.comID ?? "";
    setSessionKey(
      userAccount,
      roles,
      id,
      userNiChen,
      userPhone,
      isAdmin,
      userHeader,
      loginUrl,
      companyID,
      aiFalg,
      comID
    );
  }
}

/** 删除`token`以及key值为`user-info`的session信息 */
export function removeToken() {
  Cookies.remove(TokenKey);
  sessionStorage.clear();
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return "Bearer " + token;
};
